
<template>
    <tm-app class="phoneLogin" bgImg="white" :style="{paddingTop:systemInfo.statusBarHeight+'px'}">
        
        <tm-navbar style="postion:relative;z-index:10;" :height="50" :margin="[0,0]" :padding="[0,0]" :isPlace="false" :fontSize="32" title="绑定手机号" :transprent="true">
			<!-- <template v-slot:right>
				<tm-icon _class="px-32" name="tmicon-plus"></tm-icon>
			</template>  -->
		</tm-navbar>
        <view class="content psr" style="z-index:10;">
            <view class="inps">
                <view class="inp_box d-flex a-center" :class="{focus:inp1Focus}">
                    <view class="pre d-flex a-center j-center">
                        <view class="txt d-flex a-center j-center">+86</view>
                        <view style="height:40rpx;border-right:1px solid#ccc;"></view>
                    </view>
                    <input @focus="inp1Focus=true" @blur="inp1Blur" maxlength="11" type="number" class="inp"  v-model="phoneNum" placeholder="请输入11位手机号"/>
                </view>
                <view class="inp_box d-flex a-center" style="margin-top:20rpx;" :class="{focus:inp2Focus}">
                    <view class="pre d-flex a-center j-center">
                        <view class="txt d-flex a-center j-center">
                            <i class="tmicon tmicon-key" style="font-size:30rpx;"></i>
                        </view>
                        <view style="height:40rpx;border-right:1px solid#ccc;"></view>
                    </view>
                    <input @focus="inp2Focus=true" @blur="inp2Blur" maxlength="6" type="number" class="inp" style="width:280rpx;" v-model="vailCode" placeholder="请输入验证码"/>
                    <view v-show="showGetCode" class="btn d-flex a-center j-center" @tap="getCode">
                        <text class="text1">获取验证码</text>
                    </view>
                    <view v-show="!showGetCode" class="btn seconds d-flex a-center">{{ seconds }}</view>
                </view>

                <!-- <view class="inp_box d-flex a-center j-between" style="margin-top:40rpx;" :class="{focus:inp2Focus}">
                    <input @focus="inp2Focus=true" @blur="inp2Blur" maxlength="6" type="number" class="inp" style="width:300rpx;margin-left:10rpx;text-align: center;"  v-model="vailCode" placeholder="请输入验证码"/>
                    <view v-show="showGetCode" class="btn d-flex a-center j-center" @tap="getCode">
                        <text class="text1">获取验证码</text>
                    </view>
                    <view v-show="!showGetCode" class="btn d-flex a-center j-center">{{ seconds }}</view>
                </view> -->
            </view>



            <view class="btn_main d-flex a-center j-center" @tap="bindPhone">绑定手机号</view>




            <!-- <view v-show="loginType==='code'" class="uline pasawordLogin d-flex a-center j-center c_main" @tap="loginType='password'">
                密码登录
            </view>


            <view v-show="loginType==='password'" class="pasawordLogin d-flex a-center j-between">
                <text class="c_main uline"  @tap="loginType='code'">验证码登录</text>
                <text class="uline">忘记密码?</text>
            </view> -->

            <view class="bottom_box d-flex d-c a-center">
                <tm-checkbox
                    class="check"
                    outlined
                    v-model="readed"
                    @change="handleCheck"
                    :size="28"
                    :font-size="22"
                    color="#23e2a6"
                    :value="true"
                    label=""
                >
                    <view class="read">
                        我已阅读并同意<text class="uline" @tap="goUserAgreement">《用户协议》</text>、<text class="uline" @tap="goPrivacyPolicy">《隐私协议》</text>
                    </view>
                
                </tm-checkbox>
            </view>



            

        </view>
        <tm-message
            ref="msg"
            :width="340"
            :height="96"
            color="#9F9F9F"
            :round="6"
            :padding="[0, 0, 0, 0]"
            :margin="[0, 0, 0, 0]"
            :lines="2"
        ></tm-message>

        <uni-popup ref="popup" background-color="transparent" @change="change">
				<view class="popup-content">
                    <view class="title d-flex a-center j-center">
                        提示
                    </view>
                    <view v-show="couldMerge" class="f28 d-flex a-center j-center bold">该手机号已注册:</view>
                    <view v-show="!couldMerge" class="f28 d-flex a-center j-center bold">该手机号已注册.并绑定了微信号:</view>
                    <!-- <view class="line"></view> -->
                    <view class="userMsg f28 d-flex a-center j-center">
                        <image class="head" :src="bindUserData.data.photo?bindUserData.data.photo:'/static/head.jpg'"></image>
                        <text> {{bindUserData.data.nickName?bindUserData.data.nickName[0]:''}}** </text>
                    </view>
                    <view class="f28 d-flex a-center j-center" style="color:#2E2E30;" v-show="couldMerge">是否绑定至当前微信?</view>
                    <view class="f28 d-flex a-center j-center" style="color:#2E2E30;" v-show="!couldMerge">无法再次绑定,如果要换绑微信,请登录后在设置中更改。</view>
                    <view class="btns" v-show="couldMerge">
                        <view class="btn btn2 d-flex a-center j-center" @tap="mergeBind">确定</view>
                        <view class="btn btn1 d-flex a-center j-center" @tap="closePop">取消</view>
                    </view>
                    <view class="btns d-flex a-center j-center" v-show="!couldMerge">
                        <view class="btn btn2 d-flex a-center j-center" @tap="closePop">知道了</view>
                    </view>

                </view>
			</uni-popup>

            <!-- 
            <tm-checkbox class="check" outlined v-model="readed" @change="aaa" color="green" :value="true" label="我已阅读并同意《用户协议》、《隐私协议》"></tm-checkbox> -->
    </tm-app>
</template>

<script setup lang="ts">
import { ref,reactive } from "vue";
import { onReady, onShow,onLoad } from "@dcloudio/uni-app";
import { getVerCode,bindPhoneByCode,mergeAccount,getUserDetail } from "@/api/api";
import md5 from 'js-md5';
import { imLogin } from '@/hooks/imLogin'
import { config as configStore } from "@/store/config";
import { userData as userDataStore } from "@/store/userData";
const config: any = configStore();
const handleCheck = (bool:Boolean) => {
    config.setConfig({agreement:bool});

};

const userStore = userDataStore();

const userData:any = ref(JSON.parse(uni.getStorageSync("FIRST_USERDATA")))
const msg:any = ref(null);

import { systemInfo as  systemInfoStore}  from '@/store/systemInfo'


const systemInfo:any = systemInfoStore();


const inp1Focus = ref(false);
const inp2Focus = ref(false);

const phoneNum = ref(null);
const vailCode = ref(null);
const phoneError = ref(false);
const seconds = ref(60);
const showGetCode = ref(true);
const readed = ref(false);
const couldMerge = ref(false);

const bindUserData:any = reactive({data:{}});

const goUserAgreement = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=用户协议&url=http://52pp365.com/yonghuxieyi.html`
	});
}

const goPrivacyPolicy = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=隐私政策&url=http://52pp365.com/yinsizhengce.html`
	});
}


const inp1Blur = ()=>{
    inp1Focus.value=false;
    const bool = uni.$tm.u.isPhone(phoneNum.value);
    phoneError.value = !bool;
}

const inp2Blur = ()=>{
    inp2Focus.value=false;
}

const bindPhoneLoading = ref(false);

const bindPhone = async ()=>{

    if(bindPhoneLoading.value){
        return;
    }

    if(!readed.value){
        uni.showToast({
            icon: "none",
            title: "请先勾选并同意《用户协议》和《隐私协议",
            duration: 1500,
        });

        bindPhoneLoading.value = false;
        return
    }

    if(!vailCode.value){
        uni.showToast({
            icon: "none",
            title: "请输入正确的验证码",
            duration: 1500,
        });

        return
    }





    const params = {
        phone:phoneNum.value,
        id:userData.value.id,
        authCode:md5(vailCode.value)
    }



    const res:any = await bindPhoneByCode(params);
    const {flag,message,data} = res;

    if(flag===1){
        uni.setStorageSync("FIRST_USERDATA","");
        userStore.clearUserData();
        userData.value.phone = phoneNum.value;
        userStore.setUserData(userData.value);
        uni.setStorageSync('USER_DATA',userData.value);

        imLogin(userData.value.id);

        uni.showToast({
            icon: "none",
            title: "绑定成功",
            duration: 1500,
        });

        //imLogin(userData.id);
    }else{
        bindUserData.data = data;
        if(flag===1100){
            couldMerge.value = true
            openPop();
        }else if(flag===1101){
            couldMerge.value = false
            openPop();
        }else{
            uni.showToast({
                icon: "none",
                title: "绑定失败，请重试",
                duration: 1500,
            });
        }
    }
}







const getCode = async ()=>{
    seconds.value = 60;
    showGetCode.value = false;
    const bool = uni.$tm.u.isPhone(phoneNum.value);
    if(!bool){
        uni.showToast({
                icon: "none",
                title: "您输入的手机号有误，请检查",
                duration: 1500,
            });
        return
    }

    const res:any = await getVerCode({phone:phoneNum.value,messageType:'2'});
    const { flag } = res;
    if(flag===1){
        uni.showToast({
                icon: "none",
                title: "验证码已成功发送",
                duration: 1500,
            });
        let int = setInterval(()=>{

            if(seconds.value===1){
                showGetCode.value = true;
                clearInterval(int);
                return
            }

            seconds.value = seconds.value-1
        },1000)
    }else{
        uni.showToast({
                icon: "none",
                title: "获取验证码失败，请重试",
                duration: 1500,
            });
    }
    
}


const popup:any = ref(null);

const change = ()=>{
    popup.value.open('center')
}

const openPop = ()=>{
    popup.value.open('center')
}

const closePop = ()=>{
    popup.value.close()
}


const GetUserData = async (userId: string) => {
    const detail: any = await getUserDetail({ id: userId });
    const { flag, data } = detail;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: '获取用户信息失败，请稍后再试',
            duration: 1500,
        });
        return
    }
    const { photo } = data;

    userStore.clearUserData();
    if(photo){
        userStore.setUserData(data);
        uni.setStorageSync('USER_DATA',data);
    }
    return data;
};


const mergeBind = async ()=>{
    if(!readed.value){
        uni.showToast({
                icon: "none",
                title: "请先勾选并同意《用户协议》和《隐私协议》",
                duration: 1500,
            });
        return
    }

    if(!vailCode.value){
        uni.showToast({
                icon: "none",
                title: "请输入正确的验证码",
                duration: 1500,
            });
        return
    }





    const params = {
        phone:phoneNum.value,
        id:userData.value.id,
        authCode:md5(vailCode.value),
        openid:userData.value.openid
    }



    const res:any = await mergeAccount(params);
    const {flag,message,data} = res;

    const { id, token } = data;

    
    if(flag===1){
        userStore.clearUserData();
        uni.showToast({
                icon: "none",
                title: "绑定成功",
                duration: 1500,
        });

        const obj = await GetUserData(id);
        uni.setStorageSync("FIRST_USERDATA","");
        uni.setStorageSync("api_token", token);
        imLogin(id,null);
		


        // setTimeout(()=>{
        //     uni.redirectTo({
        //         url: '/pages/login/login',
        //         animationType: 'none',
        //     });

        // },2000)
        //imLogin(userData.value.id,null);
    }else{
        uni.showToast({
                icon: "none",
                title: message||'绑定失败',
                duration: 1500,
            });
    }
    
}




onLoad(()=>{
    // setTimeout(()=>{
    //     popup.value.open('center')
    // },1000)
})

onReady(() => {
    //popup.value.open('center');
});

onShow(() => {
    readed.value = config.agreement;
});
</script>

<style lang="scss" scoped>

.popup-content{
    width:582rpx;
    border-radius: 30rpx;
    background:#fff;
    padding:40rpx;
    overflow:hidden;
    background-image: url("~@/static/dialog-bg.png");
    background-size:100% 100%;
    .title{
        font-size:38rpx;
        color:$slim-text2;
        width:100%;
        font-weight:bold;
        margin-bottom:20rpx;

    }
    .line{
        width:100%;
        height:1px;
        background-color:#ddd;
        margin:20rpx 0;
    }
    .userMsg{
        margin:40rpx;
        .head{
            width:70rpx;
            height:70rpx;
            border-radius: 10rpx;
            margin-right:10rpx;
            

        }
    }

    .btns{
        width:100%;
        margin-top:40rpx;
        .btn{
            width:479rpx;
            height:78rpx;
            border-radius: 20rpx;
            color:#fff;
            font-size:32rpx;
            &:active{
                opacity: .7;
            }
        }
        .btn1{
            background:#fff;
            color:$slim-main;
            border:1px solid $slim-main;
            margin-top:20rpx;
        }
        .btn2{
            
            background:$slim-main;
        }
    }
}
.phoneLogin{ 
    .content{
        padding:0 60rpx;
        padding-top:50rpx;
    }

    .inps{
        width:100%;
        .desp{
            padding:20rpx;
            font-size:28rpx;
            color:#999;

        }

        // .inp_box{
        //     width:100%;
        //     height:100rpx;
        //     border:1px solid #ddd;
        //     border-radius: 20rpx;
        //     padding:20rpx;
        //     &.focus{
        //         border:1px solid $slim-main;
        //     }
        //     &.error{
        //         border:1px solid $slim-error;
        //     }
        //     .pre{
        //         width:100rpx;
        //         color:#666;
        //         font-size:32rpx;
        //     }
        //     .inp{
        //         width:450rpx;
        //         font-size:32rpx;
        //     }

        //     .text1{
        //             color:$slim-main;
        //         }
        //         .text2{
        //             color:#999;
        //         }

        //     .btn{
        //         color:$slim-main;
        //         width:200rpx;
        //         height:100%;
        //         &.btn1{
        //             width:100rpx;
        //             justify-content: flex-end;
        //         }
        //         .tmicon{
        //             font-size:40rpx;
        //             color:#999;
        //         }
        //         &:active{
        //             opacity: .7;
        //         }
        //     }
        // }
        .inp_box{
            width:570rpx;
            height:82rpx;
            border:1px solid #ddd;
            border-radius: 20rpx;
            padding:20rpx;
            margin:0 auto;
            &.focus{
                border:1px solid $slim-main;
            }
            &.error{
                border:1px solid $slim-error;
            }
            .pre{
                width:100rpx;
                color:#666;
                font-size:28rpx;
                margin-right:20rpx;
                .txt{
                    width:80rpx;
                }
            }
            .inp{
                width:460rpx;
                font-size:28rpx;
            }

            .text1{
                    color:$slim-main;
                }
                .text2{
                    color:#999;
                }

            .btn{
                color:$slim-main;
                width:200rpx;
                height:100%;
                font-size:28rpx;
                &.btn1{
                    width:50rpx;
                    justify-content: flex-end;
                }
                &.seconds{
                    justify-content: flex-end;
                    color:#999;
                }
                .tmicon{
                    font-size:40rpx;
                    color:#999;
                }
                &:active{
                    opacity: .7;
                }
            }
        }
    }

    .btn_main{
        width:570rpx;
        height:86rpx;
        background:$slim-main;
        border-radius: 20rpx;
        margin:0 auto;
        margin-top:40rpx;
        color:#fff;
        font-size:32rpx;
        &:active{
            opacity: .7;
        }
        
    }

    .pasawordLogin{
        width:100%;
        height:100rpx;
    }

    .bottom_box{
        position: fixed;
        width:100%;
        bottom:90rpx;
        left:0;
        .read{
            font-size:22rpx;
            color:#999;
            .uline{
                color: $slim-main;
            }
        }
    }

    .error-text{
        padding-left:160rpx;
        font-size:24rpx;
        height:60rpx;
        color:$slim-error;
        margin-bottom:20rpx;
    }
}
</style>
